package com.tl.commonlibrary.ui.user;


import com.tl.commonlibrary.event.EventUtil;
import com.tl.commonlibrary.event.LoginStatusEvent;
import com.tl.commonlibrary.storage.database.DBManager;
import com.tl.commonlibrary.storage.database.dao.UserDao;
import com.tl.commonlibrary.ui.beans.User;

import java.util.List;

/**
 * Created by Administrator on 2017/6/12 0012.
 */

public class Account {
    private static User user;
    public static int LEVEL_ID = Integer.MIN_VALUE;

    public static synchronized User getUser() {
        if (user == null) {
            if (DBManager.getUserDao() != null) {
                List<User> users = DBManager.getUserDao().loadAll();
                if (users != null && !users.isEmpty()) {
                    user = users.get(0);
                }
            }
        }
        return user;
    }

    public static void setUserNoEvent(User newUser) {
        setUser(newUser, false);
    }

    public static void setUser(User newUser) {
        setUser(newUser, true);
    }

    public static void setUser(User newUser, boolean event) {
        synchronized (Account.class) {
            UserDao userDao = DBManager.getUserDao();
            if (newUser != null) {//新用户
                user = newUser;
                if (userDao != null) {
                    userDao.insertOrReplace(user);
                }
                if (event) {
                    EventUtil.post(new LoginStatusEvent(LoginStatusEvent.LOGGIN));
                }
            } else {//注销
                if (user != null) {//如果注销过，不再注销
                    if (userDao != null) {
                        userDao.delete(user);
                    }
                    user = null;
                    EventUtil.post(new LoginStatusEvent(LoginStatusEvent.LOGOFF));
                }
            }
        }
    }


    public static String getToken() {
        if (getUser() != null) {
            return getUser().getToken();
        }
        return "";
    }

    public static String getUid() {
        if (getUser() != null) {
            return getUser().getUid();
        }
        return "";
    }

    public static String getMobile() {
        if (getUser() != null) {
            return getUser().getMobile();
        }
        return "";
    }

    public static int getLevelId() {
        if (getUser() != null) {
            return getUser().getLevelId();
        }
        return LEVEL_ID;
    }

    public static boolean isLogged() {
        return getUser() == null ? false : true;
    }

    public static boolean isNotLogged() {
        return !isLogged();
    }

    public static void logOff() {
        setUser(null);
    }
}
